package com.tanhua.server.controller;

import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserService userService;

    /**
     * 发送登录的验证码
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map) throws Exception {
        //1、获取到手机号码
        String phone = (String) map.get("phone");
        //2、生成6位数字验证码
        //String code = RandomUtil.randomNumbers(6);
        String code = "123456";
        //3、发送短信
        //smsTemplate.sendSms(phone,code);
        //4、存入到redis中，设置失效时间
        redisTemplate.opsForValue().set("CODE_"+phone,code,5, TimeUnit.MINUTES);
        //构造返回
        return ResponseEntity.ok(null);
    }

    //为了测试服务提供者，是否搭建成功
//    @GetMapping("/{mobile}")
//    public ResponseEntity findUser(@PathVariable("mobile") String mobile) {
//        User user = userService.findByMobile(mobile);
//        return ResponseEntity.ok(user);
//    }

    /**
     * 用户登录
     *   请求连接：POST   /loginVerification
     *   请求参数：body   phone  verificationCode （Map）
     *   返回值：
     *      token
     *      isNew
     *      封装到一个对象中（Map）
     */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map) {
        //1、获取请求参数phone和verificationCode
        String phone = (String) map.get("phone");
        String verificationCode = (String) map.get("verificationCode");
        //2、调用service完成业务处理，返回Map（token，isNew）
        Map retMap = userService.loginVerification(phone,verificationCode);
        //3、构造返回
        return ResponseEntity.ok(retMap);
    }
}
